package channel

import (
	"context"

	"gitee.com/liuxuezhan/ar-platform/assets-rpc/internal/dao/schema/user/channel"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/pkg/xerrors"
	"gitee.com/liuxuezhan/ar-platform/assets-rpc/rpc"
	"github.com/zeromicro/go-zero/core/logc"
	"github.com/zeromicro/go-zero/core/logx"
	"gorm.io/gorm"
)

type BankModel struct {
	ctx context.Context
	db  *gorm.DB
	logx.Logger
}

func (m *BankModel) getDB() *gorm.DB {
	return m.db
}

func NewBankModel(ctx context.Context, db *gorm.DB) *BankModel {
	return &BankModel{
		ctx:    ctx,
		db:     db,
		Logger: logx.WithContext(ctx),
	}
}

func (m *BankModel) UserBankDelete(in *rpc.UserBankDelRequest) (*rpc.UserBankDelResponse, error) {
	bank := channel.UserChannelBank{}

	del := m.db.Where("id = ?", in.Id)
	if in.UserId != 0 {
		del.Where("user_id = ?", in.UserId)
	}
	tx := del.Delete(&bank)
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrDel
	}

	return &rpc.UserBankDelResponse{
		IsDel: true,
	}, nil
}

// ------------------user channel bank ------------------
func (m *BankModel) UserBankInfo(in *rpc.UserBankInfoRequest) (*rpc.UserBankInfoResponse, error) {
	var userBankInfos []*channel.UserChannelBank
	var userBankInfoList []*rpc.UserBankInfo

	// 查询所有用户银行信息
	query := m.db
	if in.UserId != 0 {
		query = query.Where("user_id = ?", in.UserId)
	}
	if in.Username != "" {
		query = query.Where("user_name LIKE ?", "%"+in.Username+"%")
	}
	if in.CardNumber != "" {
		query = query.Where("card_number = ?", in.CardNumber)
	}
	if in.BankId != 0 {
		query = query.Where("bank_id = ?", in.BankId)
	}
	if in.IfscCode != "" {
		query = query.Where("ifsc_code = ?", in.IfscCode)
	}
	if in.Phone != "" {
		query = query.Where("phone = ?", in.Phone)
	}
	if in.Email != "" {
		query = query.Where("email = ?", in.Email)
	}
	if in.Province != "" {
		query = query.Where("province = ?", in.Province)
	}
	if in.City != "" {
		query = query.Where("city = ?", in.City)
	}
	if in.BranchBank != "" {
		query = query.Where("branch_bank LIKE ?", "%"+in.BranchBank+"%")
	}
	if in.AgentId != 0 {
		query = query.Where("agent_id = ?", in.AgentId)
	}
	if in.StartTime != 0 {
		query = query.Where("update_at > ? and update_at < ?", in.StartTime, in.EndTime)
	}

	tx := query.Find(&userBankInfos)
	if tx.Error != nil {
		return nil, tx.Error
	}

	for _, userBankInfo := range userBankInfos {
		userBankInfo := &rpc.UserBankInfo{
			Id:         userBankInfo.ID,
			UserId:     userBankInfo.UserId,
			UserName:   userBankInfo.UserName,
			CardNumber: userBankInfo.CardNumber,
			BankId:     userBankInfo.BankId,
			IfscCode:   userBankInfo.IfscCode,
			Phone:      userBankInfo.Phone,
			Email:      userBankInfo.Email,
			Province:   userBankInfo.Province,
			City:       userBankInfo.City,
			BranchBank: userBankInfo.BranchBank,
			BankName:   "",
			AgentId:    userBankInfo.AgentId,
		}
		userBankInfoList = append(userBankInfoList, userBankInfo)
	}

	return &rpc.UserBankInfoResponse{
		UserBankInfo: userBankInfoList,
	}, nil
}

func (m *BankModel) UserBankInfoPage(in *rpc.UserBankInfoPageRequest) (*rpc.UserBankInfoPageResponse, error) {
	var userBankInfos []*channel.UserChannelBank
	offset := in.Page.PageSize * (in.Page.PageNo - 1)

	// 查询所有用户银行信息
	query := m.db.Model(&channel.UserChannelBank{})
	if in.Param.UserId != 0 {
		query = query.Where("user_id = ?", in.Param.UserId)
	}
	if in.Param.Username != "" {
		query = query.Where("user_name LIKE ?", "%"+in.Param.Username+"%")
	}
	if in.Param.CardNumber != "" {
		query = query.Where("card_number = ?", in.Param.CardNumber)
	}
	if in.Param.BankId != 0 {
		query = query.Where("bank_id = ?", in.Param.BankId)
	}
	if in.Param.IfscCode != "" {
		query = query.Where("ifsc_code = ?", in.Param.IfscCode)
	}
	if in.Param.Phone != "" {
		query = query.Where("phone = ?", in.Param.Phone)
	}
	if in.Param.Email != "" {
		query = query.Where("email = ?", in.Param.Email)
	}
	if in.Param.Province != "" {
		query = query.Where("province = ?", in.Param.Province)
	}
	if in.Param.City != "" {
		query = query.Where("city = ?", in.Param.City)
	}
	if in.Param.BranchBank != "" {
		query = query.Where("branch_bank LIKE ?", "%"+in.Param.BranchBank+"%")
	}
	query.Order("updated_at desc")
	var total int64
	query = query.Count(&total).Limit(int(in.Page.PageSize)).Offset(int(offset))
	tx := query.Find(&userBankInfos)

	var userBankInfoList []*rpc.UserBankInfo
	if tx.Error != nil {
		return &rpc.UserBankInfoPageResponse{
			DataList: userBankInfoList,
			Total:    total,
		}, tx.Error
	}

	for _, bankInfo := range userBankInfos {
		userBankInfoList = append(userBankInfoList, &rpc.UserBankInfo{
			Id:         bankInfo.ID,
			UserId:     bankInfo.UserId,
			UserName:   bankInfo.UserName,
			CardNumber: bankInfo.CardNumber,
			Email:      bankInfo.Email,
			IfscCode:   bankInfo.IfscCode,
			Phone:      bankInfo.Phone,
			BankId:     bankInfo.BankId,
			Province:   bankInfo.Province,
			City:       bankInfo.City,
			BranchBank: bankInfo.BranchBank,
			UpdatedAt:  bankInfo.Model.UpdatedAt,
			AgentId:    bankInfo.AgentId,
		})
	}
	return &rpc.UserBankInfoPageResponse{
		DataList: userBankInfoList,
		Total:    total,
	}, nil
}

func (m *BankModel) UserBankInsert(in *rpc.UserBankInfoInsertRequest) (*rpc.UserBankInfoInsertResponse, error) {

	tx := m.db.Create(&channel.UserChannelBank{
		UserId:   in.UserId,
		UserName: in.Username,

		CardNumber: in.CardNumber,
		Email:      in.Email,
		Phone:      in.Phone,
		BankId:     in.BankId,
		Province:   in.Province,
		City:       in.City,
		IfscCode:   in.IfscCode,
		BranchBank: in.BranchBank,
	})
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrInsert
	}

	return &rpc.UserBankInfoInsertResponse{
		IsInsert: true,
	}, nil
}

func (m *BankModel) UserBankUpdate(in *rpc.UserBankInfoUpdateRequest) (*rpc.UserBankInfoUpdateResponse, error) {
	tx := m.db.Where("id = ?", in.Id).Updates(&channel.UserChannelBank{
		UserId:     in.UserId,
		UserName:   in.Username,
		CardNumber: in.CardNumber,
		IfscCode:   in.IfscCode,
		Email:      in.Email,
		Phone:      in.Phone,
		BankId:     in.BankId,
		Province:   in.Province,
		City:       in.City,
		BranchBank: in.BranchBank,
	})
	if tx.Error != nil || tx.RowsAffected == 0 {
		return nil, xerrors.ErrUpdate
	}

	return &rpc.UserBankInfoUpdateResponse{
		IsUpdate: true,
	}, nil
}

func (m *BankModel) CountShowUser(userId int64) int64 {
	var res int64

	query := m.getDB().Model(&channel.UserChannelBank{}).
		Where("user_id = ?", userId)

	tx := query.Count(&res)
	if tx.Error != nil {
		logc.Error(m.ctx, tx.Error)
		return 0
	}

	return res
}
